package cn.circle.mobile.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;


import cn.circle.mobile.dao.IUserDao;
import cn.circle.mobile.service.IUserService;
import cn.circle.redis.IRedisService;
import cn.circle.system.model.SysUser;
import cn.circle.system.util.CookieUtils;
import cn.circle.system.util.ReturnInfo;

@Service
public class UserServiceImpl implements IUserService {

	@Autowired
	private IUserDao userDao;
	
	@Autowired
	private IRedisService redisService;
	
	@Value("${REDIS_USER_SESSION_KEY}")
	private String REDIS_USER_SESSION_KEY;
	
	@Value("${SSO_SESSION_EXPIRE}")
	private Long SSO_SESSION_EXPIRE;
	
	@Override
	public Boolean register(SysUser c) {
		// TODO Auto-generated method stub
		return userDao.register(c);
	}

	@Override
	public ReturnInfo login(String phone, String userPwd,HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub
		List<SysUser> cml = userDao.login(phone,userPwd);
		ReturnInfo info = new ReturnInfo();
		if(cml.isEmpty()){
			info.setSuccess(1);
			info.setMsg("不存在此用户");			
		}else{
			if(cml.get(0).getPhone().equals(phone) && cml.get(0).getPassWord().equals(userPwd)){
				
				////构造登录 redis对象
				String token = UUID.randomUUID().toString();
				redisService.set(REDIS_USER_SESSION_KEY + ":" + token, phone ,SSO_SESSION_EXPIRE);		
				//添加写cookie的逻辑，cookie的有效期是关闭浏览器就失效。
				CookieUtils.setCookie(request, response, "USER_TOKEN", token);
				/*HashMap<String, String> map = new HashMap<>();
				map.put("USER_TOKEN", token);
				map.put("phone", phone);*/
				info.setObj(token);
			}else{
				info.setSuccess(1);
				info.setMsg("用户名或密码错误");				
			}
		}
		return info;
	}

	@Override
	public String getUserByToken(String token) {
		// TODO Auto-generated method stub
		//根据token从redis中查询用户信息
		String json = redisService.get(REDIS_USER_SESSION_KEY + ":" + token);
		//判断是否为空
		if (StringUtils.isBlank(json)) {
					return null;
			}
		//更新过期时间
		redisService.expire(REDIS_USER_SESSION_KEY + ":" + token, SSO_SESSION_EXPIRE);
		//返回用户信息
		return json;
	}

	@Override
	public  boolean delteByToken(String token, HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub
		redisService.delete(REDIS_USER_SESSION_KEY + ":" + token);
		CookieUtils.deleteCookie(request, response, "USER_TOKEN");
		return true;
	}

}
